package com.fairytask.ui.login
{
	import com.fairytask.engine.GameStage;
	import com.fairytask.engine.components.button.Button;
	import com.fairytask.engine.components.clip.Clip;
	import com.fairytask.engine.components.radioButton.RadioButton;
	import com.fairytask.engine.components.radioButton.RadioButtonGroup;
	import com.fairytask.engine.define.ResConfig;
	import com.fairytask.net.CustomToServerRequest;
	import com.fairytask.net.NetSocket;
	import com.fairytask.resource.StaticIni;
	import com.fairytask.ui.base.FrameUI;
	import com.greensock.TweenLite;
	import com.greensock.easing.Cubic;
	import com.smartfoxserver.v2.entities.data.ISFSObject;
	import com.smartfoxserver.v2.entities.data.SFSObject;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;

	/**
	 * 创建人物UI 
	 * @author yangj
	 * 
	 */	
	public class CreateRoleUI extends FrameUI
	{
		private static var _self	:CreateRoleUI;
		public var personModel	:Clip;			//当前人物的资源
		public var buttonBG			:Clip;			//右边选项框的背景
		public var startGame		:Button;		//进入游戏
		public var returnLogin		:Button;		//返回登入
		public var maleChk			:RadioButton;		//男子
		public var femaleChk		:RadioButton;		//女子
		public var randomBtn		:Button;		//随机名字
		
		private var _cSex			:int;			//选中的性别
		private var _sexGroup			:RadioButtonGroup;  //显示的单选框
		private var _randomName		:TextField;			//人物名称
		private var _fNameArray		:Array	=	[];	//姓
		private var _lNameMale			:Array	=	[];	//男子名字
		private var _lNameFemale		:Array	=	[];	//女子名字
		private var itemSpace			:Sprite	=	new Sprite();  //效果的容器
		
		public static function getInstance():CreateRoleUI
		{
			if(_self == null)
			{
				_self	=	new CreateRoleUI();
			}
			return _self;
		}
		public function CreateRoleUI(popupUI:Boolean=false)
		{
			super(popupUI);
			//初始化数据
			init();
			initEvent();
		}
		
		private function init():void
		{
			//动画效果
//			_desTimeLine	=	new TimelineLite();
//			_roleTimeLine	=	new TimelineLite();
			//性别
			_sexGroup = new RadioButtonGroup();
			maleChk.group	=	_sexGroup;
			maleChk.select	=	true;
			femaleChk.group	=	_sexGroup;
			//随机名称
			returnLogin.visible = false;
			_randomName	=	new TextField();
			_randomName.type	=	TextFieldType.INPUT;
			var dt	:TextFormat	=	new TextFormat(null,null,0xFFFFFF);
			_randomName.defaultTextFormat	=	dt;
			_randomName.maxChars=8;
			_randomName.x	=	640;
			_randomName.y	=	465;
			_randomName.width	=	110;
			windowBG.addChild(_randomName);
			//解析随机姓名
			_fNameArray	=	StaticIni.getIniList("F_Name");
			_lNameMale	=	StaticIni.getIniList("M_Name");
			_lNameFemale=	StaticIni.getIniList("FM_Name");

			//onChangeName();
			//默认选中 蜀山男
			//按钮排列在最上面
			windowBG.setChildIndex(startGame,windowBG.numChildren-1);
			windowBG.setChildIndex(returnLogin,windowBG.numChildren-1);

			this.tabEnabled = false;
			this.tabChildren = false;
		}
		
		private function initEvent():void
		{
			//返回
			returnLogin.addEventListener(MouseEvent.CLICK,onReturn);		
			//随机
			randomBtn.addEventListener(MouseEvent.CLICK,onRandom);			
			//进入游戏
			startGame.addEventListener(MouseEvent.CLICK,onStart);	
			
			//性别
			maleChk.addEventListener(MouseEvent.CLICK,onMal);
			femaleChk.addEventListener(MouseEvent.CLICK,onMal);
			//名称改变
			_randomName.addEventListener(Event.CHANGE, onNameChange);
			//后台发送弹出框消息
			//model.addEventListener(BaseNetEvent.SERVER_ERROR,onAskMsgWaitHide);
		}
		
		/*private function onAskMsgWaitHide(evt:BaseNetEvent):void
		{
			//AskMsgWaitUI.getInstance().hide();
		}*/
		
		private function onNameChange(evt:Event):void
		{
			startGame.enabled	=	true;
		}
		
		/**
		 * 默认名称 
		 * @param pStr
		 * 
		 */
		public function defaultName(pStr:String):void
		{
			_randomName.text	=	pStr;
		}
		
		/**
		 *	当选择男的时候、切换模型 
		 * @param evt
		 * 
		 */		
		private function onMal(evt:MouseEvent):void
		{
			if(_cSex==_sexGroup.curIndex)
			{
				return;
			}
			_cSex =	_sexGroup.curIndex;
			switch(_cSex)
			{
				case 0:
					personModel.source	=	ResConfig.createRolePath+"male.jpg";
					showEffect();
					break;
				case 1:
					personModel.source	=	ResConfig.createRolePath+"female.jpg";
					showEffect();
					break;
			}
			/*if(!isUserDefined())
			{
				onChangeName();
			}*/
		}
		/**
		 *效果播放 
		 * 
		 */		
		private function showEffect():void
		{
			maleChk.enabled	=	false;
			femaleChk.enabled = false;
			itemSpace.x = 600;
			itemSpace.y	= 8;
			itemSpace.addChild(personModel);
			this.addChildAt(itemSpace,0);
			itemSpace.alpha = 0;
			TweenLite.to(itemSpace,0,{alpha:1,y:10,onComplete:onAlpha});
		}
		
		/**
		 * 播放动画 
		 * 
		 */
		private function onAlpha():void
		{
			
			//弧线锚定位置				终点位置			
			TweenLite.to(itemSpace,0.5,{bezierThrough:[{x:600, y:8},{x:0, y:8}],ease:Cubic.easeOut,onComplete:onComplete});	
			
		}
		
		private function onComplete():void
		{
			maleChk.enabled	=	true;
			femaleChk.enabled = true;
			//this.removeChild(itemSpace);
		}
		
		
		/**
		 * 是否玩家自定义名称
		 * @return 
		 * 
		 */		
		private function isUserDefined():Boolean
		{
			var fName:String;
			var lName:String;
			//系统名称顶多4字符
			if(_randomName.text.length > 4)
			{
				return true;
			}
			
			//四字符(系统名称(姓2字符 + 名2字符))
			if(4 == _randomName.text.length)
			{
				fName = _randomName.text.substr(0,2);
				lName = _randomName.text.substr(2);
			}else
			{
				fName = _randomName.text.charAt(0);//姓
				lName = _randomName.text.substr(1);//名
			}
			
			//姓自定义  判断姓名是否是自定义的
			if(!isContain(_fNameArray,fName))
			{
				return true;
			}

			//名自定义(分男女)
//			if(_sexGroup.curIndex == 0)
//			{
//				if(!isContain(_lNameMale,lName))
//				{
//					return true;
//				}
//			}else
//			{
//				if(!isContain(_lNameFemale,lName))
//				{
//					return true;
//				}
//			}
			
			//名自定义不含系统内置男女名(一般玩家自定义不会用到系统内的名)
			if(!isContain(_lNameMale,lName) && !isContain(_lNameFemale,lName))
			{
				return true;
			}
			return false;
		}
		
		private function isContain(list:Array,str:String):Boolean
		{
			var tp:Array = [];
			var len:int;
			//循环把list数组中的值赋给tp数组
			while(len<list.length)
			{
				tp.push(StaticIni.getSwfLangStr(list[len]));
				len+=1;
			}
			
			//查找是否在数据库中是否有相同的姓名
			if(tp.indexOf(str) == -1)
			{
				return false;
			}else
			{
				return true;
			}
		}
		
		/**
		 * 更改姓名 
		 * 
		 */		
		private function onChangeName():void
		{
			//名字数组长度
			var fNameLen	:int	=	_fNameArray.length;
			var lFemaleLen	:int	=	_lNameFemale.length;
			var lMaleLen	:int	=	_lNameMale.length;
			
			var fName:String=StaticIni.getSwfLangStr(_fNameArray[int(Math.random()*fNameLen)]);
			var lName:String="";
			if(maleChk.select)
			{
				lName=StaticIni.getSwfLangStr(_lNameMale[int(Math.random()*lMaleLen)]);
			}
			else
			{
				lName=StaticIni.getSwfLangStr(_lNameFemale[int(Math.random()*lFemaleLen)]);
			}
			_randomName.text	=	fName+lName;
		}
		
		/**
		 *	创建角色过渡动画 
		 * 
		 */		
		private function onRoleTween(value:DisplayObject):void
		{
			
		}
		
		/**
		 *	创建角色，开始游戏 
		 * @param evt
		 * 
		 */		
		private function onStart(evt:MouseEvent):void
		{
			//不合法不执行发消息
			if(!nameValidate(_randomName.text))
			{
				return;
			}
			//进度加载界面不显示,才显示加载界面
			//AskMsgWaitUI.getInstance().onShow(-GameStage.x,-GameStage.y,GameStage.stageWidth,GameStage.stageHeight);
			startGame.enabled	=	false;
			//创建用户：角色名（string），性别（int），角色门派（int）
			var gender	:int	=	maleChk.select?1:2;
			////NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_CREATE_ROLE,_randomName.text, gender);
			var sfsObject:ISFSObject = model.getPlayerInfo();
			sfsObject.putUtfString("nickname",_randomName.text);
			NetSocket.sendCustom(CustomToServerRequest.USER_REGISTER,sfsObject);
		}
		
		/**
		 *	随机玩家名称
		 * @param evt
		 * 
		 */		
		private function onRandom(evt:MouseEvent):void
		{
			onNameChange(null);
			onChangeName();
		}
		
		/**
		 * 初始化创建前 
		 */
		override protected function BeforeShow():void
		{
			stageReSize();
			startGame.enabled	=	true;
			//平台登录，返回按钮不显示
			/*if(LoginLogic.getInstance().isPlatformLogin)
			{
				returnLogin.visible = false;
			}*/
		}
		
		/**
		 *	返回选择线路 
		 * @param evt
		 * 
		 */		
		private function onReturn(evt:MouseEvent):void
		{
			this.hide();
			//model.dispatchEvent(new LoginEvent(LoginEvent.LINESELECT));
		}
		
		/**
		 * 玩家名称校验  
		 * @param name
		 * 
		 */		
		private function nameValidate(name:String):Boolean
		{
			/*if(StringUtil.contains(name," ") || name=="" || StringUtil.contains(name,"<") || StringUtil.contains(name,">"))
			{
				var infoUI	:InfoUI	=	InfoUI.getInstance();
				infoUI.txtWithBtn(StaticIni.getSwfLangStr("1000000371"),InfoUI.SINGLEBTN,[],InfoUI.INFOTXT);
				return false;
			}*/
			return true;
		}
		
		override protected function AfterHide():void
		{
			//AskMsgWaitUI.getInstance().hide();
		}
		
		/**
		 * 重写场景变化 
		 * @param evt
		 * 
		 */
		override protected function stageReSize(evt:Event=null):void
		{
			this.graphics.beginFill(0);
			this.graphics.drawRect(-GameStage.x,-GameStage.y,GameStage.stageWidth,GameStage.stageHeight);
			this.graphics.endFill();
		}
		
		/**
		 * 重写显示 
		 * @param space
		 * @param onshow
		 * @param argc
		 * 
		 */
		override public function show(space:String=LOGINLAYER, onshow:Function=null):void
		{
			super.show(space,onshow);
		}
		
		private function onLoad():void
		{
			
		}
	}
}
